/**
 * qiniu SDK
 */
import Taro from '@tarojs/taro'

class QiniuSdk {
  constructor () {
    this.config = {
      qiniuRegion: '',
      qiniuImageURLPrefix: '',
      qiniuUploadToken: '',
      qiniuUploadTokenURL: '',
      qiniuUploadTokenFunction: null,
      qiniuShouldUseQiniuFileName: false
    }
  }
  init (options) {
    this.config = {
      qiniuRegion: '',
      qiniuImageURLPrefix: '',
      qiniuUploadToken: '',
      qiniuUploadTokenURL: '',
      qiniuUploadTokenFunction: null,
      qiniuShouldUseQiniuFileName: false
    }
    this.updateConfigWithOptions(options)
  }
  updateConfigWithOptions (options) {
    if (options.region) {
      this.config.qiniuRegion = options.region
    } else {
      console.error('qiniu uploader need your bucket region')
    }
    if (options.uptoken) {
      this.config.qiniuUploadToken = options.uptoken
    } else if (options.uptokenURL) {
      this.config.qiniuUploadTokenURL = options.uptokenURL
    } else if (options.uptokenFunc) {
      this.config.qiniuUploadTokenFunction = options.uptokenFunc
    }
    if (options.domain) {
      this.config.qiniuImageURLPrefix = options.domain
    }
    this.config.qiniuShouldUseQiniuFileName = options.shouldUseQiniuFileName
  }
  upload (filePath, success, fail, options) {
    if (filePath == null) {
      console.error('qiniu uploader need filePath to upload')
      return
    }
    if (options) {
      this.updateConfigWithOptions(options)
    }
    if (this.config.qiniuUploadToken) {
      this.doUpload(filePath, success, fail, options)
    } else if (this.config.qiniuUploadTokenURL) {
      this.getQiniuToken(() => {
        this.doUpload(filePath, success, fail, options)
      })
    } else if (this.config.qiniuUploadTokenFunction) {
      this.config.qiniuUploadToken = this.config.qiniuUploadTokenFunction()
      if (this.config.qiniuUploadToken == null && this.config.qiniuUploadToken.length > 0) {
        console.error('qiniu UploadTokenFunction result is null, please check the return value')
      }
    } else {
      console.error('qiniu uploader need one of [uptoken, uptokenURL, uptokenFunc]')
    }
  }
  doUpload (filePath, success, fail, options) {
    const {
      qiniuUploadToken,
      qiniuRegion,
      qiniuShouldUseQiniuFileName,
      qiniuImageURLPrefix
    } = this.config
    if (qiniuUploadToken == null && qiniuUploadToken.length > 0) {
      console.error('qiniu UploadToken is null, please check the init config or networking')
      return
    }
    let url = this.uploadURLFromRegionCode(qiniuRegion)
    let fileName = filePath.split('//')[1]
    if (options && options.key) {
      fileName = options.key
    }
    let formData = {
      'token': qiniuUploadToken
    }
    if (!qiniuShouldUseQiniuFileName) {
      formData['key'] = fileName
    }
    Taro.uploadFile({
      url: url,
      filePath: filePath,
      name: 'file',
      formData: formData,
      success: function (res) {
        let dataString = res.data
        try {
          let dataObject = JSON.parse(dataString)
          // do something
          let imageUrl = qiniuImageURLPrefix + '/' + dataObject.key
          dataObject.imageURL = imageUrl
          console.log(dataObject)
          if (success) {
            success(dataObject)
          }
        } catch (e) {
          console.log('parse JSON failed, origin String is: ' + dataString)
          if (fail) {
            fail(e)
          }
        }
      },
      fail: function (error) {
        console.error(error)
        if (fail) {
          fail(error)
        }
      }
    })
  }
  getQiniuToken (callback) {
    const {qiniuUploadTokenURL} = this.config
    Taro.request({
      url: qiniuUploadTokenURL,
      success: function (res) {
        const token = res.data.uptoken
        if (token && token.length > 0) {
          this.config.qiniuUploadToken = token
          if (callback) {
            callback()
          }
        } else {
          console.error('qiniuUploader cannot get your token, please check the uptokenURL or server')
        }
      },
      fail: function (error) {
        console.error('qiniu UploadToken is null, please check the init config or networking: ' + error)
      }
    })
  }
  uploadURLFromRegionCode (code) {
    let uploadURL = null
    switch (code) {
      case 'ECN':
        uploadURL = 'https://upload.qiniup.com'
        break
      case 'NCN':
        uploadURL = 'https://upload-z1.qiniup.com'
        break
      case 'SCN':
        uploadURL = 'https://upload-z2.qiniup.com'
        break
      case 'NA':
        uploadURL = 'https://upload-na0.qiniup.com'
        break
      case 'EAST2':
        uploadURL = 'https://up-cn-east-2.qiniup.com'
        break
      default:
        console.error('please make the region is with one of [ECN, SCN, NCN, NA]')
    }
    return uploadURL
  }
}

export default new QiniuSdk()
